<template>
  <div class="treePage">
    <el-input
      placeholder="请输入关键字查询"
      v-model="search"
      class="search-input"
      clearable
      @input="onSearchInput"
    ></el-input>
    <el-tree
      :data="treeData"
      node-key="id"
      default-expand-all
      :props="defaultProps"
      :filter-node-method="filterNode"
      ref="treeRef"
    ></el-tree>
  </div>
</template>

<script>
import axios from 'axios';

export default {
name: 'TreePage',
  data() {
    return {
      search: '',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    };
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.includes(value);
    },
    onSearchInput() {
      this.$refs.treeRef.filter(this.search);
    },
    fetchTreeData() {
      axios.get('http://localhost:8080/equipType/typeTree')
        .then(response => {
          this.treeData = this.transformTreeData(response.data);
        })
        .catch(error => {
          console.error('Error fetching tree data:', error);
        });
    },
    transformTreeData(data) {
      return data.map(item => ({
        id: item.EquipmentType.equipmentTypeId,
        label: item.EquipmentType.equipmentTypeName,
        children: item.Children ? this.transformTreeData(item.Children) : null
      }));
    }
  },
  mounted() {
    this.fetchTreeData();
  }
};
</script>

<style scoped>
.search-input {
  margin-bottom: 20px;
}
.treePage{
	width: 20%;
	height: 100%;
}
</style>